#!/bin/bash -e

echo `basename $0` $@ >>.log || exit 0;

sleep .005

while getopts  ":q:n:p:m:M:F" opts
do
	case  $opts  in
	p)
		cpu_num=$OPTARG
		;;
	q)
		queue=$OPTARG
		;;
	n)
		name=$OPTARG
		;;
	m)
		mem=$OPTARG
		;;
	M) email=$OPTARG;;
	F) fb=F;;
	\?)
		echo `basename $0` "[-n job_name] [-p cpu_num] [-m memery] [-q queue_name] <program and args>"
		exit 65
		;;
	esac
done
shift $(($OPTIND - 1))

if [ -z "$1" ]; then
	echo `basename $0` "[-npmq] <program and its args>"
	exit 65
fi

# maybe has no args
# if [ -z "$2" ]; then
	# echo `basename $0` "[-pm] <$1 and its args>"
	# exit 1
# fi

. $var

if [ -z "$cpu_num" ]; then
	cpu_num=9
fi

if [ -z "$mem" ]; then
	mem=29g
else 
	if
	echo $mem |grep -P '^\d+$' >/dev/null
	then
	mem=${mem}g
	fi
fi

if [ -z "$queue" ]; then
	queue=md
fi

echo queue $queue

if [ -z "$name" ]; then

	if test -z "$fb"; then
	name=_
	facebook=$tools_path/script/facebook.txt
	num1=$(rand_num.sh 1 `cat $facebook |awk 'END{print NR}'` 1)
	name=`sed -n "${num1}p" $facebook`
	else
	name=_
	fi
else
	if test -z "$fb"; then
	facebook=$tools_path/script/facebook.txt
	num1=$(rand_num.sh 1 `cat $facebook |awk 'END{print NR}'` 1)
	face=`sed -n "${num1}p" $facebook`
	name=${name}_$face
	fi
fi

# echo $@ |cat $tools_path/script/qsub_pre - | \
# qsub -N $name -q $queue -l nodes=1:ppn=$cpu_num -l mem=$mem -j oe
echo $@;

# if test -c /dev/tty; then
# exec &> /dev/tty
# else
# echo /dev/tty no exist
# fi

if test -z "$email"; then
echo $@ |cat $tools_path/script/qsub_pre - | \
qsub -N $name -q $queue -l nodes=1:ppn=$cpu_num -l mem=$mem -j oe 
else
echo $@ |cat $tools_path/script/qsub_pre - | \
qsub -N $name -M $email -m e -q $queue -l nodes=1:ppn=$cpu_num -l mem=$mem -j oe
fi


echo $1 '...' has been qsubed.
# echo $1 has been qsubed. > /dev/stdout